package com.spring.controller;

import com.spring.entity.Company;
import com.spring.service.PositionService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private PositionService positionService;

    @RequestMapping("updatePhoto.action")
    public void updatePhoto(int cid, MultipartFile photo,HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //完善2：如果文件夹在项目部署目录下
        String realPath = req.getServletContext().getRealPath("/upload");
        //完善1：如果文件夹不存在，就创建
        //File dir = new File("d:/upload");
        File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //完善3：避免同名文件覆盖
        UUID uuid = UUID.randomUUID();
        String extName = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
        String fileName = uuid.toString()+extName;
        //上传文件
        photo.transferTo(new File(dir,fileName));


        //写数据到数据库中
        Company company = new Company();
        company.setCid(cid);
        company.setPhotoName(fileName);
        company.setPhotoType(photo.getContentType());

        try {
            this.positionService.updatePhoto(company);
            resp.getWriter().print("ok");
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().print("error");
        }



    }

    @RequestMapping("downloadPhoto.action")
    public void downloadPhoto(String photoName,String photoType,
                              HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String realPath = req.getServletContext().getRealPath("/upload");
        File file = new File(realPath,photoName);
        resp.setContentType(photoType);
        resp.setContentLength((int)file.length());
        resp.setHeader("Content-Disposition", "attachment;filename="+photoName);

        InputStream is = new FileInputStream(file);
        OutputStream os = resp.getOutputStream();
        IOUtils.copy(is,os);
        is.close();
        os.close();

    }

    @RequestMapping("findAllComp.action")
    @ResponseBody
    public List<Company> findAllComp(){
        return this.positionService.findAllComp();
    }

    @RequestMapping("add.action")
    public String add(Company company, MultipartFile photo, Model model, HttpServletRequest req) throws IOException {
        //存储图片到指定目录
        //完善2：如果文件夹在项目部署目录下
        String realPath = req.getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        //完善1：如果文件夹不存在，就创建
        //File dir = new File("d:/upload");
        File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //完善3：避免同名文件覆盖
        UUID uuid = UUID.randomUUID();
        String extName = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
        String fileName = uuid.toString()+extName;
        System.out.println(fileName);
        //photo.transferTo(new File("d:/upload/"+photo.getOriginalFilename()));
        //photo.transferTo(new File(dir,photo.getOriginalFilename()));
        photo.transferTo(new File(dir,fileName));

        //保存信息到数据库
        company.setPhotoName(fileName);
        company.setPhotoType(photo.getContentType());
        try {
            this.positionService.addCompany(company);
            return "redirect:/page/companyList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error","添加失败");
            return "forward:/page/companyAdd.jsp";
        }

    }

    @RequestMapping("add2.action")
    public String add2(Company company, MultipartFile photo, Model model) throws IOException {
        //存储图片到指定目录
        File file = new File("d:/upload/"+photo.getOriginalFilename());
        photo.transferTo(file);

        //保存信息到数据库
        company.setPhotoName(photo.getOriginalFilename());
        company.setPhotoType(photo.getContentType());
        try {
            this.positionService.addCompany(company);
            return "redirect:/page/companyList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error","添加失败");
            return "forward:/page/companyAdd.jsp";
        }

    }
}
